// activity/pages/activity_invite.js
const app = getApp()
var server = require('../../utils/server');
var common = require('../../utils/common');
var counttime = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    top: 428,
    countH: '00',
    countM: '00',
    countS: '00',
    showLoginPop: false,
    detail: '',
    teamStatus: '',
    eventStatus: '',
    userType: '', //0:团长，1：成员，2：第三人
    voucherTeamId: '',
    voucherEventId: '',
    isInvite: false,
    leftTime: '',
    isLogin: true,
    param: {},
    isToBuy: false, //立即使用
    isShowLeaderAuthorize: false, //团长
    isShowMemAuthorize: false, //团员
    templatetype: "", //拼团模板类型0:开团,1:参团
    isDisableLog: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      voucherTeamId: options.teamid == undefined ? '' : options.teamid,
      voucherEventId: options.eventid == undefined ? '' : options.eventid,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.sdkversion >= 283 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      wx.hideHomeButton();
    }
    wx.getStorage({
      key: 'sso',
      success: res => {
        console.log(res)
        this.getVoucherDetail();
      },
      fail: res => {
        console.log('fail')
        this.getUserInfo();
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log(counttime)
    clearTimeout(counttime);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log(counttime)
    clearTimeout(counttime);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  // 倒计时
  countTime() {
    //获取当前时间  
    //时间差  
    var leftTime = this.data.leftTime;
    //定义变量 d,h,m,s保存倒计时的时间  
    var h, m, s;
    if (leftTime > 0) {
      h = Math.floor(leftTime / 60 / 60 % 24);
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
    } else {
      this.getVoucherDetail();
    }
    //将0-9的数字前面加上0，例1变为01
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    //将倒计时赋值到div中
    if (leftTime > 0) {
      this.setData({
        countH: h,
        countM: m,
        countS: s
      })
    }
    var that = this;
    if (leftTime >= 0) {
      counttime = setTimeout(function () {
        that.data.leftTime = parseInt(that.data.leftTime) - 1;
        that.setData({
          leftTime: that.data.leftTime
        })
        that.countTime();
      }, 1000);
    }
  },
  onShareAppMessage(options) {
    var shareObj = {
      path: '/activity/pages/activity_invite?eventid=' + this.data.voucherEventId + '&&teamid=' + this.data.voucherTeamId,
      title: this.data.detail.share_desc,
      imageUrl: this.data.detail.goods_pic_url,
      success: function (res) {},
      fail: function () {
        console.log("分享失败")
      }
    }
    return shareObj;
  },

  //获取用户信息
  getUserInfo() {
    wx.login({
      success: resp => {
        wx.getUserInfo({
          success: res => {
            this.setData({
              showLoginPop: false,
              isLogin: true
            })
            var code = resp.code,
              that = this,
              userParams = {
                "js_code": code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.locateLongitude,
                "latitude": app.globalData.locateLatitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.locateCity,
                "scene": ''
              };
            server.login(common.basePath + 'miniprogram/login/', userParams, function (res) {
              if (res.data.errno == "0") {
                wx.setStorage({
                  key: "sso",
                  data: res.data.data.sso,
                  success: ret => {
                    app.globalData.isGetWxUserinfo = true;
                    that.getVoucherDetail();
                    if (JSON.stringify(res.data.data.member) != "{}") {
                      that.storageUserinfo(res.data.data);
                    }
                  }
                })
              } else {
                common.showErrorToast(res.data.errmsg);
              }
            })
          },
          fail: res => {
            wx.removeStorage({
              key: 'userInfo',
              success: function (res) {}
            })
            this.setData({
              showLoginPop: true,
              isLogin: false
            })
          }
        })
      },
      fail: res => {
        this.setData({
          showLoginPop: true,
          isLogin: false
        })
      }
    })
  },
  //授权用户信息
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isLogin: true
      })
      var that = this
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code,
                that = this,
                userParams = {
                  "js_code": code,
                  "encryptedData": res.encryptedData,
                  "iv": res.iv,
                  "userinfo": res.userInfo,
                  "longitude": app.globalData.locateLongitude,
                  "latitude": app.globalData.locateLatitude,
                  "province": app.globalData.locateProvince,
                  "city": app.globalData.locateCity,
                  "scene": ''
                }
              server.login(common.basePath + 'miniprogram/login/', userParams, function (res) {
                if (res.data.errno == "0") {
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: ret => {
                      that.setData({
                        isDisableLog: false
                      })
                      app.globalData.isGetWxUserinfo = true;
                      that.getVoucherDetail();
                      if (JSON.stringify(res.data.data.member) != "{}") {
                        that.storageUserinfo(res.data.data)
                      }
                    }
                  })
                } else {
                  that.setData({
                    isDisableLog: false
                  })
                  common.showErrorToast(res.data.errmsg)
                }
              })
            }
          })
        }
      })
    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  getVoucherDetail() {
    wx.stopPullDownRefresh();
    server.postJSON(common.basePath + 'voucher/team/', {
      "voucher_event_id": this.data.voucherEventId,
      "voucher_team_id": this.data.voucherTeamId,
      "type": ""
    }, res => {
      if (res.data.errno == '0') {
        var data = res.data.data;
        console.log(data)
        this.setData({
          detail: data.voucher,
          eventStatus: data.voucher.status,
          teamStatus: data.voucher_team.status,
          userType: data.voucher.type,
          teamList: data.voucher_team_list
        })
        clearTimeout(counttime);
        this.data.leftTime = data.voucher_team.e_time;
        if (this.data.leftTime > 0) {
          this.countTime();
        }
        const query = wx.createSelectorQuery();
        query.select('.activity-status').boundingClientRect();
        query.select('.ticket-cont').boundingClientRect();
        query.select('.header-tit').boundingClientRect();
        query.selectViewport().scrollOffset();
        var that = this;
        query.exec(function (res) {
          console.log(res)
          that.setData({
            top: parseInt(res[0].height) + parseInt(res[1].height) + parseInt(res[2].height) + 12
          })
        })
      } else {
        if (res.data.errno == '100012' || res.data.errno == '100013') {
          this.setData({
            showLoginPop: true
          })
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      }
    })

  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  goToAccount() {
    switch (this.data.detail.event_type) {
      case '1':
        wx.navigateTo({
          url: '../../membership_supply/pages/productDetailM?eventid=' + this.data.detail.event_id + '&&goodsid=' + this.data.detail.goods.goods_id,
        })
        break;
      case '2':
        wx.navigateTo({
          url: '/membership_supply/pages/productListsM' + this.data.detail.template_id + '?eventid=' + this.data.detail.event_id,
        })
        break;
      case '3':
        wx.navigateTo({
          url: '../../pages/shop/productsListIndex',
        })
        break;
    }
  },
  goToIndex() {
    wx.switchTab({
      url: '../../pages/index/index',
    })
  },
  onPullDownRefresh() {
    this.getVoucherDetail();
  },
  showAgreement() {
    wx.navigateTo({
      url: '../../pages/common/agreement',
    })
  },
  showLoginPop() {
    this.setData({
      showLoginPop: true
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  },
  //再来一张开团
  goToOpenGroup() {
    clearTimeout(counttime);
    this.setData({
      isOpen: true
    })
    this.data.templatetype = 0;
    server.postJSON(common.basePath + 'voucher/addteam/', {
      "voucher_event_id": this.data.voucherEventId
    }, res => {
      this.setData({
        isOpen: false
      })
      if (res.data.errno == '0') {
        var data = res.data.data;
        this.data.voucherTeamId = data;
        this.setData({
          detail: ''
        })
        this.getVoucherDetail();
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //参加凑对
  joinTeam() {
    this.setData({
      isHelp: true
    })
    this.data.templatetype = 1;
    this.sendWxTemplate();

  },
  //邀请好友凑对
  getFormid() {
    this.setData({
      isInvite: true
    })
    this.data.templatetype == 0;
    this.sendWxTemplate();
    console.log('nooption')
  },
  rememberSelect() {
    server.postJSON(common.basePath + 'user/isshow', {
      "type": this.data.templatetype == 0 ? 'openteam' : "addteam",
      "is_checked": 1
    }, res => {
      if (res.data.errno == '0') {
        if (this.data.templatetype == 0) {
          this.setData({
            isShowLeaderAuthorize: false
          })
        } else if (this.data.templatetype == 1) {
          this.setData({
            isShowMemAuthorize: false
          })
        }
        this.sendWxTemplate();
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  sendWxTemplate() {
    if (app.globalData.sdkversion >= 282 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      server.postJSON(common.basePath + 'miniprogram/getnewtemplateid', {
        "type": this.data.templatetype == 0 ? 'pin' : "pinsucc"
      }, res => {
        if (res.data.errno == '0') {
          var ids = [];
          (res.data.data).forEach((item, index) => {
            ids.push(item)
          })
          var that = this;
          wx.requestSubscribeMessage({
            tmplIds: ids,
            success(res) {
              that.addTeam();
            },
            fail(res) {
              that.addTeam();
            }
          })
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法获得订阅消息通知，请升级到最新微信版本后重试。',
        success: res => {
          this.addTeam();
        }
      })
    }
  },
  addTeam() {
    if (this.data.templatetype == 0) {
      server.postJSON(common.basePath + 'voucher/addteam/', {
        "voucher_event_id": this.data.voucherEventId
      }, res => {
        this.setData({
          isOpen: false,
          isInvite: false
        })
        if (res.data.errno == '0') {
          var data = res.data.data;
          this.data.voucherTeamId = data;
          this.setData({
            detail: ''
          })
          this.getVoucherDetail();
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else if (this.data.templatetype == 1) {
      server.postJSON(common.basePath + 'voucher/jointeam/', {
        "voucher_team_id": this.data.voucherTeamId
      }, resp => {
        this.setData({
          isHelp: false
        })
        if (resp.data.errno == '0') {
          this.getVoucherDetail();
        } else {
          common.showErrorToast(resp.data.errmsg);
        }
      })
    }
  }
})